﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Security.Principal;

namespace Scrum.SwimLanes.Models
{
    /// This class can be used to impersonate the Windows account accessing 
    /// the IIS web site or virtual directory. When this object goes out of scope, the
    /// impersonation is reverted back to the original identity.
    public class HttpContextImpersonator : IDisposable
    {
        private HttpContextImpersonator()
        {
        }

        private WindowsImpersonationContext ctx = null;

        public static HttpContextImpersonator Begin()
        {
            HttpContextImpersonator impersonator = new HttpContextImpersonator();
            WindowsIdentity winId = (WindowsIdentity)HttpContext.Current.User.Identity;
            impersonator.ctx = winId.Impersonate();
            return impersonator;
        }

        public void Undo()
        {
            if (this.ctx != null)
            {
                this.ctx.Undo();
            }
        }

        #region IDisposable Members

        public void Dispose()
        {
            try
            {
                this.Undo();
            }
            catch
            {
                // eat it
            }
        }

        #endregion
    }
}